<template>
    <div class="add-product-container">
        <h2 class="section-title">添加商品</h2>
        
        <!-- 商品表单 -->
        <el-form :model="productForm" :rules="rules" ref="productFormRef" label-width="100px" class="product-form">
            <!-- 商品名称 -->
            <el-form-item label="商品名称" prop="name">
                <el-input v-model="productForm.name" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            
            <!-- 商品价格 -->
            <el-form-item label="商品价格" prop="price">
                <el-input-number v-model="productForm.price" :precision="2" :step="0.1" :min="0" controls-position="right"></el-input-number>
                <span class="form-item-tip">单位：元</span>
            </el-form-item>
            
            <!-- 商品库存 -->
            <el-form-item label="商品库存" prop="stock">
                <el-input-number v-model="productForm.stock" :min="0" controls-position="right"></el-input-number>
                <span class="form-item-tip">单位：件</span>
            </el-form-item>
            
            <!-- 商品图片 -->
            <el-form-item label="商品图片" prop="image">
                <el-upload
                    class="product-image-uploader"
                    :action="null"
                    :http-request="handleUploadRequest"
                    :show-file-list="false"
                    :before-upload="beforeImageUpload">
                    <img v-if="productForm.image" :src="imageUrl" class="product-image">
                    <el-icon v-else class="upload-icon"><Plus /></el-icon>
                </el-upload>
                <span class="form-item-tip">建议尺寸：800x800像素，大小不超过2MB</span>
            </el-form-item>
            
            <!-- 商品描述 -->
            <el-form-item label="商品描述" prop="description">
                <el-input 
                    v-model="productForm.description" 
                    type="textarea" 
                    :rows="4" 
                    placeholder="请输入商品描述，详细介绍商品特点与用途"
                ></el-input>
            </el-form-item>
            
            <!-- 提交按钮 -->
            <el-form-item>
                <el-button type="primary" @click="submitForm">保存商品</el-button>
                <el-button @click="resetForm">重置</el-button>
                <el-button @click="goBack">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
// 导入所需的组件和API
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import api from '@/assets/js/api.js';

const router = useRouter();
const productFormRef = ref(null);

// 商品表单数据
const productForm = reactive({
    name: '', // 商品名称
    price: 0, // 商品价格
    stock: 0, // 商品库存
    image: '', // 商品图片
    description: '' // 商品描述
});

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '请设置商品价格', trigger: 'blur' }
    ],
    stock: [
        { required: true, message: '请设置商品库存', trigger: 'blur' }
    ],
    image: [
        { required: true, message: '请上传商品图片', trigger: 'change' }
    ],
    description: [
        { required: true, message: '请输入商品描述', trigger: 'blur' },
        { min: 10, max: 500, message: '描述长度在10到500个字符之间', trigger: 'blur' }
    ]
};

// 计算图片完整URL
const imageUrl = computed(() => {
    if (productForm.image && !productForm.image.startsWith('http')) {
        return `http://localhost:8080${productForm.image}`;
    }
    return productForm.image;
});

// 图片上传前的验证
function beforeImageUpload(file) {
    // 检查文件类型
    const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
    if (!isImage) {
        ElMessage.error('上传的图片只能是 JPG/PNG/GIF 格式!');
        return false;
    }
    
    // 检查文件大小，限制为2MB
    const isLessThan2M = file.size / 1024 / 1024 < 2;
    if (!isLessThan2M) {
        ElMessage.error('上传的图片大小不能超过 2MB!');
        return false;
    }
    
    return isImage && isLessThan2M;
}

// 自定义上传请求
async function handleUploadRequest(options) {
    try {
        const file = options.file;
        const result = await api.uploadFile(file);
        
        if (result.code === 200) {
            productForm.image = result.data.url; // 获取url
            ElMessage.success('图片上传成功!');
        } else {
            options.onError();
            ElMessage.error('图片上传失败: ' + result.message);
        }
    } catch (error) {
        options.onError();
        ElMessage.error('图片上传失败，请稍后重试');
    }
}

// 提交表单
async function submitForm() {
    if (!productFormRef.value) return;
    
    await productFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 调用添加商品的API
                const response = await api.addProduct(productForm);
                
                if (response.code === 200) {
                    ElMessage.success('商品添加成功!');
                    // 重置表单
                    resetForm();
                    // 可选：跳转回商品列表
                    router.push('/home/products');
                } else {
                    ElMessage.error('商品添加失败: ' + response.message);
                }
            } catch (error) {
                console.error('添加商品出错:', error);
                ElMessage.error('系统错误，请稍后重试');
            }
        } else {
            ElMessage.warning('请完善商品信息');
            return false;
        }
    });
}

// 重置表单
function resetForm() {
    if (productFormRef.value) {
        productFormRef.value.resetFields();
    }
}

// 返回上一页
function goBack() {
    router.back();
}
</script>

<style scoped>
.add-product-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-title {
    font-size: 20px;
    color: #303133;
    margin-bottom: 25px;
    border-left: 4px solid #409EFF;
    padding-left: 10px;
}

.product-form {
    max-width: 800px;
}

.form-item-tip {
    margin-left: 10px;
    color: #909399;
    font-size: 12px;
}

.product-image-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 180px;
    height: 180px;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: border-color 0.3s;
}

.product-image-uploader:hover {
    border-color: #409EFF;
}

.product-image {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
}

.upload-icon {
    font-size: 28px;
    color: #8c939d;
    width: 40px;
    height: 40px;
}
</style>